package com.block.job.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.block.common.exception.NotifyExceptionService;
import com.block.common.service.LogFactory;
import com.block.db.mapper.*;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Struct;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class VerifySysTemBillJob {

    private static final Logger log = LogFactory.getJobLog();


    /**
     * 核对系统账单
     * @throws Exception
     */
    @XxlJob("verifySysTemBillJob")
    public void verifySysTemBillJob() throws Exception {
        XxlJobHelper.log("---------开始执行--------");

        checkMerchantCostBill();

        XxlJobHelper.log("数据清理 ---------结束执行--------");
    }

    @Resource
    AccountMerchantInfoHisMapper accountMerchantInfoHisMapper;
    @Resource
    MerchantDataPushInfoMapper merchantDataPushInfoMapper;


    @Autowired
    NotifyExceptionService notifyExceptionService;

    /**
     * 核对 商户账户的消耗金额  是否与 数据推送表中的数据一致
     */
    public void checkMerchantCostBill(){

        String dateInfo = LocalDate.now().minusDays(1).toString();
        // 查询当日机构的消耗总信息
        // 聚合查询
        List<Map<String, Object>> resultList = accountMerchantInfoHisMapper.selectXhMapList(dateInfo);

        StringBuilder stringBuilder = new StringBuilder();
        for (Map<String, Object> map : resultList) {

            Integer infoId = (Integer) map.get("infoId");
            String infoName = (String) map.get("infoName");
            Double totalAmountDouble = (Double) map.get("totalAmount");
            BigDecimal totalAmount = new BigDecimal(totalAmountDouble).setScale(2, RoundingMode.HALF_UP);
            totalAmount = BigDecimal.ZERO.subtract(totalAmount);

            BigDecimal xhTotalAmount = merchantDataPushInfoMapper.getXhAmountByInfoIdAndDateInfo(infoId, dateInfo);

            if (ObjectUtil.isEmpty(totalAmount) || ObjectUtil.isEmpty(xhTotalAmount) || totalAmount.compareTo(xhTotalAmount) != 0){
                String message = StrUtil.format("【{}】{}【accountAmount】{}【pushAmount】{}", infoId, infoName, totalAmount, xhTotalAmount);
                stringBuilder.append(message).append("\n");
            }
        }

        // 将消息通知发送到企业微信
        notifyExceptionService.notifyWechatShibaiException("CHECK_MERCHANT_BILL", dateInfo + " 核对商户账单", stringBuilder.toString(), null);

    }


}
